import { RefObject, useEffect, useRef } from 'react';
import { ECharts } from 'echarts';
import * as echarts from 'echarts';
import { useEvent } from 'react-use';
import { debounce } from 'lodash-es';

type EChartOption = echarts.EChartOption;

export const useEcharts = (ref: RefObject<HTMLElement>, option: EChartOption) => {
  const chartInstance = useRef<ECharts>();

  useEffect(() => {
    if (ref.current) {
      chartInstance.current = echarts.init(ref.current);
    }

    return () => {
      chartInstance.current?.dispose();
    };
  }, []);

  useEffect(() => {
    if (chartInstance.current) {
      chartInstance.current.setOption(option);
    }
  }, [option]);

  useEvent(
    'resize',
    debounce(() => {
      setTimeout(() => {
        chartInstance.current?.resize();
      }, 100);
    }, 100),
  );

  return [chartInstance];
};
